import { addQualityUser, deleteQualityUser, editQualityUser,
  findAllQualityUser, findQualityUserByPage, batchRemove } from '../services/qualityUser';

export default {
  namespace: 'qualityUser',
  state: {
    list: {
      list: [],
      pagination: {},
    },
    loading: false,
  },
  effects: {
    *fetch({ payload }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(findQualityUserByPage, payload);
      yield put({
        type: 'appendList',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
    },
    *add({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(addQualityUser, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
      if (callback) callback(response);
    },
    *update({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(editQualityUser, payload);
      yield put({
        type: 'changeLoading',
        payload: false,
      });
      if (callback) callback(response);
    },
    *del({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(deleteQualityUser, payload);
      yield put({
        type: 'changeLoading',
        payload: false,
      });
      if (callback) callback(response);
    },
    *batchRemove({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(batchRemove, payload);
      yield put({
        type: 'changeLoading',
        payload: false,
      });
      if (callback) callback(response);
    },
    *findAllQualityUser({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(findAllQualityUser, payload);
      yield put({
        type: 'changeLoading',
        payload: false,
      });
      if (callback) callback(response);
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    appendList(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
    changeLoading(state, action) {
      return {
        ...state,
        loading: action.payload,
      };
    },
  },
};
